/*
 * Copyright 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.faxsun.controller.account;

import java.net.MalformedURLException;
import java.net.URL;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpHeaders;
import org.broadleafcommerce.common.exception.ServiceException;
import org.broadleafcommerce.core.web.controller.account.BroadleafLoginController;
import org.broadleafcommerce.core.web.controller.account.ResetPasswordForm;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * The controller responsible for all actions involving logging a customer in
 */
@Controller
public class LoginController extends BroadleafLoginController {

	protected static final Log LOG = LogFactory.getLog(LoginController.class);

	@RequestMapping("/login")
	public String login(HttpServletRequest request, HttpServletResponse response, Model model) {
		String successUrl = null;

		if (StringUtils.isNotBlank(request.getParameter("successUrl"))) {
			successUrl = request.getParameter("successUrl");
		} else {
			String referer = request.getHeader(HttpHeaders.REFERER);
			if (StringUtils.isNotBlank(referer)) {
				try {
					URL refererUrl = new URL(referer);
					if (!request.getContextPath().equals("/")
							&& refererUrl.getFile().startsWith(request.getContextPath())) {
						successUrl = refererUrl.getFile().substring(request.getContextPath().length());
					}
				} catch (MalformedURLException e) {
					LOG.warn("Failed to convert referer : " + referer + " to URL.");
				}
			}
		}

		if (StringUtils.isNotBlank(successUrl)) {
			model.addAttribute("successUrl", successUrl);
		}

		return getLoginView();
	}

	@RequestMapping(value = "/login/forgotPassword", method = RequestMethod.GET)
	public String forgotPassword(HttpServletRequest request, HttpServletResponse response, Model model) {
		return super.forgotPassword(request, response, model);
	}

	@RequestMapping(value = "/login/forgotPassword", method = RequestMethod.POST)
	public String processForgotPassword(@RequestParam("emailAddress") String emailAddress,
			HttpServletRequest request, Model model) {
		return super.processForgotPassword(emailAddress, request, model);
	}

	@RequestMapping(value = "/login/resetPassword", method = RequestMethod.GET)
	public String resetPassword(HttpServletRequest request, HttpServletResponse response, Model model) {
		return super.resetPassword(request, response, model);
	}

	@RequestMapping(value = "/login/resetPassword", method = RequestMethod.POST)
	public String processResetPassword(
			@ModelAttribute("resetPasswordForm") ResetPasswordForm resetPasswordForm,
			HttpServletRequest request, HttpServletResponse response, Model model, BindingResult errors)
			throws ServiceException {
		return super.processResetPassword(resetPasswordForm, request, response, model, errors);
	}

	@Override
	public String getResetPasswordUrl(HttpServletRequest request) {
		String url = request.getScheme() + "://" + request.getServerName()
				+ getResetPasswordPort(request, request.getScheme());

		if (request.getContextPath() != null && !"".equals(request.getContextPath())) {
			url = url + request.getContextPath() + "/login/resetPassword";
		} else {
			url = url + "/login/resetPassword";
		}
		return url;
	}

	@RequestMapping(value = "/login/sessionExpired", method = RequestMethod.GET)
	public String processSessionExpired() {
		return "authentication/sessionExpired";
	}
}
